package com.browsesoft.arrange;

import java.sql.SQLException;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.browsesoft.ExtendElement;
import com.browsesoft.ManagerGroup;
import com.browsesoft.dbtools.DBTools;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLTreeModel;
import com.browsesoft.htmlcomponent.Template;
import com.browsesoft.htmlcomponent.TemplateManager;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2003
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author not attributable
 * @version 1.0
 */
public class ArrangeTreeModel implements HTMLTreeModel {
	Arrange root = null;

	/**
	 * 初始化model
	 * 
	 * @throws Exception
	 */

	public void init(HttpServletRequest request) throws Exception {
	}

	/**
	 * 取得根结点
	 * 
	 * @return 根结点
	 */
	public Object getRootNode() throws Exception {
		return root;
	}

	/**
	 * 设置链接内容
	 * 
	 * @param nodeLink
	 *            链接'
	 * @param modelNode
	 *            树节点对应的model的节点
	 */
	public void setContextNode(Element nodeLink, Object modelNode)
			throws Exception {
	}

	/**
	 * 根据结点返回子结点
	 * 
	 * @return 子结点
	 */
	public LinkedList getChildNodes(Object node) throws Exception {
		return ((Arrange) node).getChildren();
	}

	/**
	 * 根据结点返回结点的名称
	 * 
	 * @return 结点的名称
	 */
	public String getName(Object node) throws Exception {
		return ((Arrange) node).getName();
	}

	/**
	 * 根据结点返回结点的id
	 * 
	 * @return 结点的名称
	 */
	public String getID(Object node) throws Exception {
		return ((Arrange) node).getID();
	}

	/**
	 * 根据id找到结点对象
	 * 
	 * @return 结点对象
	 */
	public Object getObject(String ID) throws Exception {
		return Arrange.getArrange(ID);
	}

	/**
	 * 处理用户请求
	 * 
	 * @param request
	 *            客户端请求
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (request.getParameter("formName") != null) {
			String templateName = request.getParameter("formName");
			TemplateManager manager = (TemplateManager) ManagerGroup
					.getManagerGroup().getManager("template");
			// 根据模板名生成模板
			Template t = manager.getTemplateByName(templateName);
			// 得到模板文档
			Document document = t.getDocument();
			// 解析文档,找出需要处理的根元素
			Element root = (Element) document.getElementsByTagName("body")
					.item(0);
			// 找到有属性fieldtype的元素
			LinkedList list = ExtendElement.findElementsOfAttr(root,
					"fieldtype");
			// 取得表名
			String tableName = ((Element) root.getElementsByTagName("form")
					.item(0)).getAttribute("name");
			// 找到所有分类元素
			list = this.findArrangeElements(list);
			// 构造多级分类
			constructArranges(list, tableName);
		}
	}

	public void setContextNode() {
	}

	public void constructArranges(LinkedList elements, String tableName)
			throws Exception {
		// 构造根分类
		root = new Arrange("分类", "");
		root.setRoot(true);
		// 找到有几极分类
		int index = findArrangeIndex(elements);
		for (int i = 0; i < index; i++) {
			// 首先找到i级的分类，存入LinkedList
			LinkedList v = findArrangeElements(elements, i + 1);
			LinkedList temp = new LinkedList();
			// 找到第几层孙子
			temp.addAll(root.getGardensons(i));
			for (int j = 0; j < temp.size(); j++) {
				Arrange r = (Arrange) temp.get(j);
				addArranges(r, v, tableName);
			}
		}
	}

	public void addArranges(Arrange root, LinkedList v, String tableName)
			throws Exception {
		for (int i = 0; i < v.size(); i++) {
			try {
				Element e = (Element) v.get(i);
				String field = e.getAttribute("name");
				// 构造每一层的根分类
				Arrange a = new Arrange(e.getAttribute("cname"), field);
				a.setRoot(true);
				// 添加到根中
				root.add(a);
				// 创建根的子分类
				if (!field.equals("")) {
					String sql = "select " + field + " from " + tableName
							+ " group by " + field;
					// 取得分类结果
					String[][] r = DBTools.executeQueryWithTableHead(sql);
					LinkedList result = new LinkedList();
					for (int j = 1; j < r.length; j++) {
						result.add(r[j][0]);
					}
					// 循环构造子分类
					for (int j = 0; j < result.size(); j++) {
						if (!((String) result.get(j)).equals("")) {
							Arrange child = new Arrange((String) result.get(j),
									field);
							child.setRoot(false);
							// 添加到父分类
							a.add(child);
						}
					}
				}
			} catch (SQLException s) {
				System.out.println("分类检索数据库出错");
			}
		}
	}

	// 找到有几极分类个数
	public int findArrangeIndex(LinkedList elements) {
		int index = 0;
		for (int i = 0; i < elements.size(); i++) {
			Element e = (Element) elements.get(i);
			int j = Integer.parseInt(e.getAttribute("arrangetype"));
			if (j > index) {
				index = j;
			}
		}
		return index;
	}

	// 找到所有的分类元素
	public LinkedList findArrangeElements(LinkedList elements) {
		LinkedList temp = new LinkedList();
		// 首先找到所有带分类标签的元素
		for (int i = 0; i < elements.size(); i++) {
			Element e = (Element) elements.get(i);
			if ((e.getAttribute("arrangetype") != null)
					&& (!e.getAttribute("arrangetype").equals(""))) {
				temp.add(e);
			}
		}
		return temp;
	}

	// 找到第index级的分类元素
	public LinkedList findArrangeElements(LinkedList elements, int index) {
		LinkedList temp = new LinkedList();
		// 首先找到所有带分类标签的元素
		for (int i = 0; i < elements.size(); i++) {
			Element e = (Element) elements.get(i);
			String str = e.getAttribute("arrangetype");
			if (Integer.parseInt(str) == index) {
				temp.add(e);
			}
		}
		return temp;
	}

	/**
	 * 设置模型所对应的组件
	 * 
	 * @param component
	 *            对应的组件
	 */
	public void setComponent(HTMLBasicComponent component) {
	}

	/**
	 * 模型更新页面元素
	 * 
	 * @throws Exception
	 */
	public void updatePageElement(HTMLBasicComponent c) throws Exception {
	}

	/**
	 * 得到节点对应的图标
	 * 
	 * @param node
	 *            节点
	 * @return 图标
	 */
	public String getIcon(Object node) {
		return null;
	}
}
